import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 缓存管理器
class CacheManager {
  constructor(options = {}) {
    this.cache = new Map()
    this.maxAge = options.maxAge || 5 * 60 * 1000 // 默认缓存5分钟
    this.maxSize = options.maxSize || 100 // 默认最大缓存100条
  }

  // 设置缓存
  set(key, value) {
    if (this.cache.size >= this.maxSize) {
      // 删除最旧的缓存
      const oldestKey = this.cache.keys().next().value
      this.cache.delete(oldestKey)
    }

    this.cache.set(key, {
      value,
      timestamp: Date.now()
    })
  }

  // 获取缓存
  get(key) {
    const item = this.cache.get(key)
    if (!item) return null

    // 检查缓存是否过期
    if (Date.now() - item.timestamp > this.maxAge) {
      this.cache.delete(key)
      return null
    }

    return item.value
  }

  // 清除缓存
  clear() {
    this.cache.clear()
  }

  // 删除指定缓存
  delete(key) {
    this.cache.delete(key)
  }
}

// 图表渲染优化器
class ChartOptimizer {
  constructor() {
    this.charts = new Map()
    this.resizeObserver = null
    this.resizeTimeout = null
  }

  // 初始化图表
  initChart(chartRef, chartInstance, options = {}) {
    if (!chartRef || !chartInstance) return

    const chartId = chartRef.id || `chart-${Date.now()}`
    this.charts.set(chartId, {
      instance: chartInstance,
      options: {
        throttle: options.throttle || 100,
        debounce: options.debounce || 200
      }
    })

    // 设置图表容器ID
    chartRef.id = chartId

    // 初始化resize观察器
    this.initResizeObserver(chartRef)
  }

  // 初始化resize观察器
  initResizeObserver(chartRef) {
    if (!this.resizeObserver) {
      this.resizeObserver = new ResizeObserver(this.handleResize.bind(this))
    }
    this.resizeObserver.observe(chartRef)
  }

  // 处理resize事件
  handleResize(entries) {
    if (this.resizeTimeout) {
      clearTimeout(this.resizeTimeout)
    }

    this.resizeTimeout = setTimeout(() => {
      entries.forEach(entry => {
        const chartId = entry.target.id
        const chart = this.charts.get(chartId)
        if (chart) {
          chart.instance.resize()
        }
      })
    }, 200)
  }

  // 销毁图表
  destroyChart(chartRef) {
    if (!chartRef) return

    const chartId = chartRef.id
    const chart = this.charts.get(chartId)
    if (chart) {
      chart.instance.dispose()
      this.charts.delete(chartId)
      this.resizeObserver?.unobserve(chartRef)
    }
  }

  // 销毁所有图表
  destroyAllCharts() {
    this.charts.forEach(chart => {
      chart.instance.dispose()
    })
    this.charts.clear()
    this.resizeObserver?.disconnect()
  }
}

// 数据预加载器
class DataPreloader {
  constructor(options = {}) {
    this.queue = new Map()
    this.maxConcurrent = options.maxConcurrent || 3
    this.retryTimes = options.retryTimes || 3
    this.retryDelay = options.retryDelay || 1000
  }

  // 添加预加载任务
  addTask(key, task, priority = 0) {
    this.queue.set(key, {
      task,
      priority,
      status: 'pending',
      retryCount: 0
    })
  }

  // 执行预加载任务
  async executeTasks() {
    const tasks = Array.from(this.queue.entries())
      .filter(([_, task]) => task.status === 'pending')
      .sort((a, b) => b[1].priority - a[1].priority)

    const executingTasks = tasks.slice(0, this.maxConcurrent)
    const promises = executingTasks.map(([key, task]) => this.executeTask(key, task))

    await Promise.all(promises)
  }

  // 执行单个任务
  async executeTask(key, task) {
    try {
      task.status = 'executing'
      await task.task()
      task.status = 'completed'
      this.queue.delete(key)
    } catch (error) {
      if (task.retryCount < this.retryTimes) {
        task.retryCount++
        task.status = 'pending'
        setTimeout(() => {
          this.executeTask(key, task)
        }, this.retryDelay * task.retryCount)
      } else {
        task.status = 'failed'
        console.error(`预加载任务执行失败: ${key}`, error)
        ElMessage.error(`数据预加载失败: ${error.message}`)
      }
    }
  }

  // 清除所有任务
  clearTasks() {
    this.queue.clear()
  }
}

// 导出工具实例
export const cacheManager = new CacheManager()
export const chartOptimizer = new ChartOptimizer()
export const dataPreloader = new DataPreloader()

// 导出工具函数
export function usePerformance() {
  const loading = ref(false)
  const error = ref(null)

  // 带缓存的数据加载
  const loadDataWithCache = async (key, loader, options = {}) => {
    try {
      // 检查缓存
      const cachedData = cacheManager.get(key)
      if (cachedData && !options.force) {
        return cachedData
      }

      loading.value = true
      error.value = null

      // 加载数据
      const data = await loader()
      
      // 设置缓存
      if (!options.noCache) {
        cacheManager.set(key, data)
      }

      return data
    } catch (err) {
      error.value = err
      throw err
    } finally {
      loading.value = false
    }
  }

  // 优化图表渲染
  const optimizeChart = (chartRef, chartInstance, options = {}) => {
    chartOptimizer.initChart(chartRef, chartInstance, options)
  }

  // 预加载数据
  const preloadData = (key, loader, priority = 0) => {
    dataPreloader.addTask(key, loader, priority)
  }

  // 执行预加载
  const executePreload = () => {
    return dataPreloader.executeTasks()
  }

  // 清理资源
  const cleanup = () => {
    cacheManager.clear()
    chartOptimizer.destroyAllCharts()
    dataPreloader.clearTasks()
  }

  return {
    loading,
    error,
    loadDataWithCache,
    optimizeChart,
    preloadData,
    executePreload,
    cleanup
  }
} 